package com.honghe.system.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.honghe.common.utils.DateUtils;
import com.honghe.common.utils.SecurityUtils;
import com.honghe.system.domain.SysAttendance;
import com.honghe.system.domain.SysAttendanceLeave;
import com.honghe.system.mapper.SysAttendanceMapper;
import com.honghe.system.mapper.SysAttendanceLeaveMapper;
import com.honghe.system.service.ISysAttendanceLeaveService;

/**
 * 请假申请Service业务层处理
 * 
 * @author honghe
 */
@Service
public class SysAttendanceLeaveServiceImpl implements ISysAttendanceLeaveService 
{
    @Autowired
    private SysAttendanceLeaveMapper sysAttendanceLeaveMapper;
    
    @Autowired
    private SysAttendanceMapper sysAttendanceMapper;

    /**
     * 查询请假申请
     * 
     * @param leaveId 请假申请主键
     * @return 请假申请
     */
    @Override
    public SysAttendanceLeave selectSysAttendanceLeaveByLeaveId(Long leaveId)
    {
        return sysAttendanceLeaveMapper.selectSysAttendanceLeaveByLeaveId(leaveId);
    }

    /**
     * 查询请假申请列表
     * 
     * @param sysAttendanceLeave 请假申请
     * @return 请假申请
     */
    @Override
    public List<SysAttendanceLeave> selectSysAttendanceLeaveList(SysAttendanceLeave sysAttendanceLeave)
    {
        return sysAttendanceLeaveMapper.selectSysAttendanceLeaveList(sysAttendanceLeave);
    }

    /**
     * 新增请假申请
     * 
     * @param sysAttendanceLeave 请假申请
     * @return 结果
     */
    @Override
    public int insertSysAttendanceLeave(SysAttendanceLeave sysAttendanceLeave)
    {
        sysAttendanceLeave.setCreateTime(DateUtils.getNowDate());
        return sysAttendanceLeaveMapper.insertSysAttendanceLeave(sysAttendanceLeave);
    }

    /**
     * 修改请假申请
     * 
     * @param sysAttendanceLeave 请假申请
     * @return 结果
     */
    @Override
    public int updateSysAttendanceLeave(SysAttendanceLeave sysAttendanceLeave)
    {
        sysAttendanceLeave.setUpdateTime(DateUtils.getNowDate());
        return sysAttendanceLeaveMapper.updateSysAttendanceLeave(sysAttendanceLeave);
    }

    /**
     * 批量删除请假申请
     * 
     * @param leaveIds 需要删除的请假申请主键
     * @return 结果
     */
    @Override
    public int deleteSysAttendanceLeaveByLeaveIds(Long[] leaveIds)
    {
        return sysAttendanceLeaveMapper.deleteSysAttendanceLeaveByLeaveIds(leaveIds);
    }

    /**
     * 删除请假申请信息
     * 
     * @param leaveId 请假申请主键
     * @return 结果
     */
    @Override
    public int deleteSysAttendanceLeaveByLeaveId(Long leaveId)
    {
        return sysAttendanceLeaveMapper.deleteSysAttendanceLeaveByLeaveId(leaveId);
    }
    
    /**
     * 提交请假申请
     * 
     * @param sysAttendanceLeave 请假申请
     * @return 结果
     */
    @Override
    public int applyLeave(SysAttendanceLeave sysAttendanceLeave)
    {
        // 设置用户ID
        sysAttendanceLeave.setUserId(SecurityUtils.getUserId());
        // 设置初始状态为待审批
        sysAttendanceLeave.setStatus("0");
        // 设置创建者和创建时间
        sysAttendanceLeave.setCreateBy(SecurityUtils.getUsername());
        sysAttendanceLeave.setCreateTime(DateUtils.getNowDate());
        
        // 处理请假期间的考勤记录
        Date startDate = sysAttendanceLeave.getStartTime();
        Date endDate = sysAttendanceLeave.getEndTime();
        
        // 计算请假天数
        Calendar calStart = Calendar.getInstance();
        calStart.setTime(startDate);
        calStart.set(Calendar.HOUR_OF_DAY, 0);
        calStart.set(Calendar.MINUTE, 0);
        calStart.set(Calendar.SECOND, 0);
        calStart.set(Calendar.MILLISECOND, 0);
        
        Calendar calEnd = Calendar.getInstance();
        calEnd.setTime(endDate);
        calEnd.set(Calendar.HOUR_OF_DAY, 0);
        calEnd.set(Calendar.MINUTE, 0);
        calEnd.set(Calendar.SECOND, 0);
        calEnd.set(Calendar.MILLISECOND, 0);
        
        // 遍历请假期间的每一天，更新或创建考勤记录
        while (!calStart.after(calEnd)) {
            Date currentDate = calStart.getTime();
            
            // 查询当天是否已有考勤记录
            SysAttendance attendance = new SysAttendance();
            attendance.setUserId(SecurityUtils.getUserId());
            attendance.setAttendanceDate(currentDate);
            List<SysAttendance> attendanceList = sysAttendanceMapper.selectSysAttendanceList(attendance);
            
            if (attendanceList != null && !attendanceList.isEmpty()) {
                // 如果存在考勤记录，则更新状态为请假
                SysAttendance existAttendance = attendanceList.get(0);
                existAttendance.setStatus("L");
                existAttendance.setUpdateBy(SecurityUtils.getUsername());
                existAttendance.setUpdateTime(DateUtils.getNowDate());
                sysAttendanceMapper.updateSysAttendance(existAttendance);
            } else {
                // 如果不存在考勤记录，则创建一条请假状态的考勤记录
                SysAttendance newAttendance = new SysAttendance();
                newAttendance.setUserId(SecurityUtils.getUserId());
                newAttendance.setAttendanceDate(currentDate);
                newAttendance.setStatus("L");
                newAttendance.setCreateBy(SecurityUtils.getUsername());
                newAttendance.setCreateTime(DateUtils.getNowDate());
                sysAttendanceMapper.insertSysAttendance(newAttendance);
            }
            
            // 日期加1天
            calStart.add(Calendar.DATE, 1);
        }
        
        return sysAttendanceLeaveMapper.insertSysAttendanceLeave(sysAttendanceLeave);
    }
    
    /**
     * 审批请假申请
     * 
     * @param leaveId 请假申请ID
     * @param status 审批状态
     * @param remark 审批备注
     * @return 结果
     */
    @Override
    public int approveLeave(Long leaveId, String status, String remark) {
        // 查询请假申请
        SysAttendanceLeave leave = sysAttendanceLeaveMapper.selectSysAttendanceLeaveByLeaveId(leaveId);
        if (leave == null) {
            return 0;
        }
        
        // 更新请假申请状态
        leave.setStatus(status);
        leave.setRemark(remark);
        leave.setUpdateBy(SecurityUtils.getUsername());
        leave.setUpdateTime(DateUtils.getNowDate());
        
        // 如果审批通过，处理请假期间的考勤记录
        if ("1".equals(status)) {
            Date startDate = leave.getStartTime();
            Date endDate = leave.getEndTime();
            
            // 计算请假天数
            Calendar calStart = Calendar.getInstance();
            calStart.setTime(startDate);
            calStart.set(Calendar.HOUR_OF_DAY, 0);
            calStart.set(Calendar.MINUTE, 0);
            calStart.set(Calendar.SECOND, 0);
            calStart.set(Calendar.MILLISECOND, 0);
            
            Calendar calEnd = Calendar.getInstance();
            calEnd.setTime(endDate);
            calEnd.set(Calendar.HOUR_OF_DAY, 0);
            calEnd.set(Calendar.MINUTE, 0);
            calEnd.set(Calendar.SECOND, 0);
            calEnd.set(Calendar.MILLISECOND, 0);
            
            // 遍历请假期间的每一天，更新考勤记录状态为已批准的请假
            while (!calStart.after(calEnd)) {
                Date currentDate = calStart.getTime();
                
                // 查询当天是否已有考勤记录
                SysAttendance attendance = new SysAttendance();
                attendance.setUserId(leave.getUserId());
                attendance.setAttendanceDate(currentDate);
                List<SysAttendance> attendanceList = sysAttendanceMapper.selectSysAttendanceList(attendance);
                
                if (attendanceList != null && !attendanceList.isEmpty()) {
                    // 如果存在考勤记录，则更新状态为已批准的请假
                    SysAttendance existAttendance = attendanceList.get(0);
                    existAttendance.setStatus("L");
                    existAttendance.setRemark("请假已批准: " + leave.getLeaveType());
                    existAttendance.setUpdateBy(SecurityUtils.getUsername());
                    existAttendance.setUpdateTime(DateUtils.getNowDate());
                    sysAttendanceMapper.updateSysAttendance(existAttendance);
                } else {
                    // 如果不存在考勤记录，则创建一条已批准请假状态的考勤记录
                    SysAttendance newAttendance = new SysAttendance();
                    newAttendance.setUserId(leave.getUserId());
                    newAttendance.setAttendanceDate(currentDate);
                    newAttendance.setStatus("L");
                    newAttendance.setRemark("请假已批准: " + leave.getLeaveType());
                    newAttendance.setCreateBy(SecurityUtils.getUsername());
                    newAttendance.setCreateTime(DateUtils.getNowDate());
                    sysAttendanceMapper.insertSysAttendance(newAttendance);
                }
                
                // 日期加1天
                calStart.add(Calendar.DATE, 1);
            }
        } else if ("2".equals(status)) {
            // 如果驳回请假申请，将相关考勤记录恢复为正常状态
            Date startDate = leave.getStartTime();
            Date endDate = leave.getEndTime();
            
            // 计算请假天数
            Calendar calStart = Calendar.getInstance();
            calStart.setTime(startDate);
            calStart.set(Calendar.HOUR_OF_DAY, 0);
            calStart.set(Calendar.MINUTE, 0);
            calStart.set(Calendar.SECOND, 0);
            calStart.set(Calendar.MILLISECOND, 0);
            
            Calendar calEnd = Calendar.getInstance();
            calEnd.setTime(endDate);
            calEnd.set(Calendar.HOUR_OF_DAY, 0);
            calEnd.set(Calendar.MINUTE, 0);
            calEnd.set(Calendar.SECOND, 0);
            calEnd.set(Calendar.MILLISECOND, 0);
            
            // 遍历请假期间的每一天，更新考勤记录状态
            while (!calStart.after(calEnd)) {
                Date currentDate = calStart.getTime();
                
                // 查询当天是否已有考勤记录
                SysAttendance attendance = new SysAttendance();
                attendance.setUserId(leave.getUserId());
                attendance.setAttendanceDate(currentDate);
                List<SysAttendance> attendanceList = sysAttendanceMapper.selectSysAttendanceList(attendance);
                
                if (attendanceList != null && !attendanceList.isEmpty()) {
                    // 如果存在考勤记录，则恢复状态
                    SysAttendance existAttendance = attendanceList.get(0);
                    if ("L".equals(existAttendance.getStatus())) {
                        // 只有当状态为请假时才恢复
                        existAttendance.setStatus(existAttendance.getClockInTime() != null && existAttendance.getClockOutTime() != null ? "normal" : 
                                                 existAttendance.getClockInTime() != null ? "no_out" : "no_in");
                        existAttendance.setRemark("请假已驳回");
                        existAttendance.setUpdateBy(SecurityUtils.getUsername());
                        existAttendance.setUpdateTime(DateUtils.getNowDate());
                        sysAttendanceMapper.updateSysAttendance(existAttendance);
                    }
                }
                
                // 日期加1天
                calStart.add(Calendar.DATE, 1);
            }
        }
        
        return sysAttendanceLeaveMapper.updateSysAttendanceLeave(leave);
    }
} 